package com.dhz.common.solr.server;

import com.dhz.common.utils.StrExtUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 配置一个{@link HttpSolrClient} 操作solr服务器上的指定core
 *
 * @author Fyduan
 */
public class HttpSolrClientFactory extends SolrClientFactoryBase {

    private String core;

    protected HttpSolrClientFactory() {}

    public HttpSolrClientFactory(SolrClient solrClient) {
        this(solrClient, null);
    }

    public HttpSolrClientFactory(SolrClient solrClient, String core) {
        super(solrClient);
        Assert.notNull(solrClient, "SolrClientFactory不能为null");

        this.core = core;

        appendCoreToBaseUrl(core, this.getSolrClient());
    }

    protected void appendCoreToBaseUrl(String core, SolrClient solrClient) {
        if (StrExtUtils.isNotEmpty(core) && isHttpSolrClient(solrClient)) {
            HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient;

            String baseUrl = SolrClientUtils.appendCoreToBaseUrl(httpSolrClient.getBaseURL(), core);
            httpSolrClient.setBaseURL(baseUrl);
        }
    }

    @Override
    public SolrClient getSolrClient(String coreName) {
        return getSolrClient();
    }

    @Override
    public List<String> getCores() {
        return this.core == null ? Collections.emptyList() : Arrays.asList(this.core);
    }

}
